import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Statistic,
  Progress,
  List,
  Avatar,
  Button,
  Tag,
  Typography,
  Space,
  Divider,
  Badge,
} from 'antd';
import {
  ArrowUpOutlined,
  ArrowDownOutlined,
  UserAddOutlined,
  TeamOutlined,
  FileTextOutlined,
  HeartOutlined,
  RightOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { Line, Column, Pie } from '@ant-design/charts';
import { useNavigate } from 'react-router-dom';
import { statsAPI } from '@/services/api';
import { DashboardStats } from '@/types';

const { Title, Text } = Typography;

interface StatCardData {
  title: string;
  value: number;
  change: number;
  icon: React.ReactNode;
  color: string;
}

interface QuickAction {
  title: string;
  description: string;
  icon: React.ReactNode;
  path: string;
  badge?: number;
}

interface PendingTask {
  id: string;
  title: string;
  type: 'review' | 'match' | 'certification';
  user: string;
  time: string;
  priority: 'high' | 'medium' | 'low';
}

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [dashboardStats, setDashboardStats] = useState<DashboardStats | null>(null);

  // 加载仪表板数据
  const loadDashboardData = async () => {
    try {
      setLoading(true);
      const response = await statsAPI.getDashboardStats();
      if (response.success) {
        setDashboardStats(response.data);
      }
    } catch (error) {
      console.error('加载仪表板数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadDashboardData();
  }, []);

  // 核心指标数据
  const statCards: StatCardData[] = [
    {
      title: '今日新增用户',
      value: dashboardStats?.todayNewUsers || 0,
      change: 12.5,
      icon: <UserAddOutlined />,
      color: '#52c41a',
    },
    {
      title: '活跃用户数',
      value: dashboardStats?.activeUsers || 0,
      change: -2.3,
      icon: <TeamOutlined />,
      color: '#1890ff',
    },
    {
      title: '待审核资料',
      value: dashboardStats?.pendingReviews || 0,
      change: 8.7,
      icon: <FileTextOutlined />,
      color: '#fa8c16',
    },
    {
      title: '今日牵线成功',
      value: dashboardStats?.todayMatches || 0,
      change: 15.2,
      icon: <HeartOutlined />,
      color: '#eb2f96',
    },
  ];

  // 快捷入口
  const quickActions: QuickAction[] = [
    {
      title: '待审核列表',
      description: '查看待审核的用户资料',
      icon: <FileTextOutlined />,
      path: '/user/review',
      badge: 89,
    },
    {
      title: '未读互动消息',
      description: '处理用户互动记录',
      icon: <HeartOutlined />,
      path: '/match/interaction',
      badge: 23,
    },
    {
      title: '数据报表',
      description: '查看详细数据分析',
      icon: <TeamOutlined />,
      path: '/statistics/operation',
    },
  ];

  // 待处理任务
  const pendingTasks: PendingTask[] = [
    {
      id: '1',
      title: '用户李小花的资料审核',
      type: 'review',
      user: '李小花',
      time: '2分钟前',
      priority: 'high',
    },
    {
      id: '2',
      title: '王明与张丽的匹配建议',
      type: 'match',
      user: '王明',
      time: '5分钟前',
      priority: 'medium',
    },
    {
      id: '3',
      title: '学历认证申请处理',
      type: 'certification',
      user: '陈志强',
      time: '10分钟前',
      priority: 'medium',
    },
  ];

  // 用户增长趋势数据
  const userGrowthData = [
    { date: '2024-01', users: 1200 },
    { date: '2024-02', users: 1350 },
    { date: '2024-03', users: 1480 },
    { date: '2024-04', users: 1620 },
    { date: '2024-05', users: 1780 },
    { date: '2024-06', users: 1920 },
    { date: '2024-07', users: 2100 },
  ];

  // 匹配成功率数据
  const matchSuccessData = [
    { hour: '00:00', rate: 12 },
    { hour: '06:00', rate: 8 },
    { hour: '12:00', rate: 25 },
    { hour: '18:00', rate: 35 },
    { hour: '21:00', rate: 28 },
    { hour: '23:00', rate: 15 },
  ];

  // 用户分布数据
  const userDistributionData = [
    { type: '男性用户', value: 52 },
    { type: '女性用户', value: 48 },
  ];

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return '#ff4d4f';
      case 'medium': return '#fa8c16';
      case 'low': return '#52c41a';
      default: return '#d9d9d9';
    }
  };

  const getTypeTag = (type: string) => {
    switch (type) {
      case 'review': return <Tag color="orange">资料审核</Tag>;
      case 'match': return <Tag color="pink">匹配建议</Tag>;
      case 'certification': return <Tag color="blue">认证申请</Tag>;
      default: return <Tag>未知</Tag>;
    }
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <Title level={4} className="page-title">数据概览</Title>
        <Text className="page-description">
          欢迎回来！这里是系统的整体数据概览，您可以快速了解平台运营情况。
        </Text>
      </div>

      {/* 核心指标卡片 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        {statCards.map((card, index) => (
          <Col xs={24} sm={12} lg={6} key={index}>
            <Card className="stat-card" bodyStyle={{ padding: '20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <Text type="secondary" style={{ fontSize: '14px' }}>
                    {card.title}
                  </Text>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', margin: '8px 0' }}>
                    {card.value.toLocaleString()}
                  </div>
                  <Space>
                    {card.change > 0 ? (
                      <ArrowUpOutlined style={{ color: '#52c41a' }} />
                    ) : (
                      <ArrowDownOutlined style={{ color: '#ff4d4f' }} />
                    )}
                    <Text 
                      style={{ 
                        color: card.change > 0 ? '#52c41a' : '#ff4d4f',
                        fontSize: '12px'
                      }}
                    >
                      {Math.abs(card.change)}%
                    </Text>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      较昨日
                    </Text>
                  </Space>
                </div>
                <div style={{ 
                  fontSize: '32px', 
                  color: card.color,
                  opacity: 0.8
                }}>
                  {card.icon}
                </div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 关键转化率 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col span={24}>
          <Card title="关键转化率" bodyStyle={{ padding: '20px' }}>
            <Row gutter={[24, 24]}>
              <Col xs={24} md={8}>
                <div style={{ textAlign: 'center' }}>
                  <Progress
                    type="circle"
                    percent={dashboardStats?.profileApprovalRate || 0}
                    format={percent => `${percent}%`}
                    strokeColor="#52c41a"
                    size={120}
                  />
                  <div style={{ marginTop: '12px' }}>
                    <Text strong>资料通过率</Text>
                  </div>
                </div>
              </Col>
              <Col xs={24} md={8}>
                <div style={{ textAlign: 'center' }}>
                  <Progress
                    type="circle"
                    percent={dashboardStats?.matchResponseRate || 0}
                    format={percent => `${percent}%`}
                    strokeColor="#1890ff"
                    size={120}
                  />
                  <div style={{ marginTop: '12px' }}>
                    <Text strong>匹配响应率</Text>
                  </div>
                </div>
              </Col>
              <Col xs={24} md={8}>
                <div style={{ textAlign: 'center' }}>
                  <Progress
                    type="circle"
                    percent={dashboardStats?.paidConversionRate || 0}
                    format={percent => `${percent}%`}
                    strokeColor="#fa8c16"
                    size={120}
                  />
                  <div style={{ marginTop: '12px' }}>
                    <Text strong>付费转化率</Text>
                  </div>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      <Row gutter={[24, 24]}>
        {/* 用户增长趋势 */}
        <Col xs={24} xl={12}>
          <Card title="用户增长趋势（近7个月）" bodyStyle={{ padding: '20px' }}>
            <Line
              data={userGrowthData}
              xField="date"
              yField="users"
              smooth={true}
              point={{ size: 5, shape: 'diamond' }}
              color="#1890ff"
              height={300}
            />
          </Card>
        </Col>

        {/* 匹配成功率热力图 */}
        <Col xs={24} xl={12}>
          <Card title="匹配成功率（按时段）" bodyStyle={{ padding: '20px' }}>
            <Column
              data={matchSuccessData}
              xField="hour"
              yField="rate"
              color="#eb2f96"
              height={300}
              columnWidthRatio={0.6}
            />
          </Card>
        </Col>

        {/* 快捷入口 */}
        <Col xs={24} xl={8}>
          <Card title="快捷入口" bodyStyle={{ padding: '20px' }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              {quickActions.map((action, index) => (
                <Card
                  key={index}
                  size="small"
                  hoverable
                  style={{ cursor: 'pointer' }}
                  onClick={() => navigate(action.path)}
                  bodyStyle={{ padding: '12px 16px' }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                      <div style={{ fontSize: '18px', color: '#1890ff' }}>
                        {action.icon}
                      </div>
                      <div>
                        <Text strong>{action.title}</Text>
                        {action.badge && (
                          <Badge
                            count={action.badge}
                            style={{ marginLeft: '8px' }}
                          />
                        )}
                        <br />
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          {action.description}
                        </Text>
                      </div>
                    </div>
                    <RightOutlined style={{ color: '#d9d9d9' }} />
                  </div>
                </Card>
              ))}
            </Space>
          </Card>
        </Col>

        {/* 待处理任务 */}
        <Col xs={24} xl={8}>
          <Card 
            title="待处理任务" 
            extra={<Button type="link" size="small">查看全部</Button>}
            bodyStyle={{ padding: '20px' }}
          >
            <List
              dataSource={pendingTasks}
              renderItem={(task) => (
                <List.Item style={{ padding: '12px 0' }}>
                  <List.Item.Meta
                    avatar={
                      <div style={{ 
                        width: '8px', 
                        height: '8px', 
                        borderRadius: '50%', 
                        backgroundColor: getPriorityColor(task.priority),
                        marginTop: '6px'
                      }} />
                    }
                    title={
                      <Space>
                        <Text strong style={{ fontSize: '14px' }}>
                          {task.title}
                        </Text>
                        {getTypeTag(task.type)}
                      </Space>
                    }
                    description={
                      <Space>
                        <ClockCircleOutlined style={{ fontSize: '12px' }} />
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          {task.time}
                        </Text>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 用户性别分布 */}
        <Col xs={24} xl={8}>
          <Card title="用户性别分布" bodyStyle={{ padding: '20px' }}>
            <Pie
              data={userDistributionData}
              angleField="value"
              colorField="type"
              radius={0.8}
              height={250}
              label={{
                type: 'outer',
                content: '{name} {percentage}',
              }}
              interactions={[{ type: 'element-active' }]}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;